/**
 * Created by Administrator on 2016/6/2 0002.
 */

var AppService = {
  urlroot: "http://euvee.vicp.co/rest/fdb/",
  init: function () {
    Vue.http.options.root = this.urlroot;
  },
  //初始化引入数据
  find: function (inputQuery, pagenum, pagesteps, items, success_callback, error_callback) {
    var url = this.urlroot;
    Vue.http.get(url, function (data, status, request) {
      var i = data.length;
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
      if (error_callback != null) {
        error_callback(data, status, request);
      }
    });
  },
  find2: function (inputQuery, pagenum, pagesteps, user, begtime, endtime, success_callback, error_callback) {
    Vue.http.get(this.urlroot + "filter?user=" + user + "&begtime=" + begtime + "&endtime=" + endtime, function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
      if (error_callback != null) {
        error_callback(data, status, request);
      }
    });
  },
  add: function (items, success_callback, error_callback) {
    Vue.http.post(this.urlroot, items, function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
      if (error_callback != null) {
        error_callback(data, status, request);
      }
    });
  },
  //绑定id，删除数据
  remove: function (item, success_callback, error_callback) {
    Vue.http.delete(this.urlroot + item.uuid, function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
      if (error_callback != null) {
        error_callback(data, status, request);
      }
    })
  },
//修改节点信息
  edit: function (item, success_callback, error_callback) {
    Vue.http.put(this.urlroot + item.uuid, item, function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
        if (error_callback != null) {
          error_callback(data, status, request);
        }
      }
    )
  },
  //上传
  upload: function (formData) {
    $.ajax({
      url: "http://euvee.vicp.co/file",
      data: formData,
      type: "POST",
      async: false,
      cache: false,
      contentType: false,
      processData: false
    });
  },
  //下载文件
  downloading: function (filename, day, success_callback, error_callback) {
    window.location.href = "http://euvee.vicp.co/file?filename=" + filename + "&day=" + day;
  },
  //显示详情
  details: function (item, success_callback, error_callback) {
    Vue.http.get(this.urlroot + item.uuid, function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
        if (error_callback != null) {
          error_callback(data, status, request);
        }
      }
    )
  },
  //返回父级目录
  backToParent: function (p, success_callback, error_callback) {
    Vue.http.get(this.urlroot + p + "/children", function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
        if (error_callback != null) {
          error_callback(data, status, request);
        }
      }
    );
  },
  backToParent2: function (parentid, success_callback, error_callback) {
    Vue.http.get(this.urlroot + parentid, function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
        if (error_callback != null) {
          error_callback(data, status, request);
        }
      }
    );
  },
//切换节点
  change: function (item, success_callback, error_callback) {
    Vue.http.get(this.urlroot + item.uuid + "/children", function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
        if (error_callback != null) {
          error_callback(data, status, request);
        }
      }
    );
  }
};
var svc = Object.create(AppService);

Vue.component('itemeditor', {
  template: '#itemeditor-tpl',
  mode: "modeEdit",
  //可以使用 props 把数据传给子组件。
  // “prop” 是组件数据的一个字段，期望从父组件传下来。子组件需要显式地用 props 选项 声明 props：
  props: [
    {
      name: 'item',
      type: Object,
      twoWay: false,
      required: true
    },
    {
      name: 'mode',
      type: String
      //default: 'modeList',
    },
    {
      name: 'onSave',
      type: Function
      //required: true,
    },
    {
      name: 'onCancel',
      type: Function
    }
  ],

  data: function () {
    return {
      result: ''
    }
  },

  methods: {
    onSubmitClick: function (e) {
      console.log("onSubmitClick: inside component itemeditor");
      this.result = vm.onSave("modeEdit", this.item);
    },
    onCancelClick: function (e) {
      console.log("onCancelClick: inside component itemeditor");
      vm.onCancel();
    }
  }
});// ------end Vue.component('itemeditor'


Vue.component('itemadd', {
  template: '#itemadd-tpl',
  //可以使用 props 把数据传给子组件。
  // “prop” 是组件数据的一个字段，期望从父组件传下来。子组件需要显式地用 props 选项 声明 props：
  props: [{
    name: 'item',
    type: Object,
    twoWay: false,
    required: true
  },
    {
      name: 'mode',
      type: String
      //default: 'modeList',
    },
    {
      name: 'onSave',
      type: Function
      //required: true,
    },
    {
      name: 'onCancel',
      type: Function
    }
  ],

  data: function () {
    return {
      result: ''
    }
  },

  methods: {
    onSubmitClick: function (e, file) {
      console.log("onSubmitClick: inside component itemadd");
      //this.result = vm.onSave("modeAddNew", this.item);
      vm.onSave("modeAddNew", this.item);
    },
    onCancelClick: function (e) {
      console.log("onCancelClick: inside component itemadd");
      vm.onCancel();
    }
  }
});// ------end Vue.component('itemeaddview'

var vm = new Vue({

  el: '#res',
  data: {
    currentView: 'itemeditor',
    begtime: '',
    endtime: '',
    items: [],
    items2: [],
    curitem: {},
    mode: 'modeList',
    modeTitle: "",
    user: '',
    searchQuery: '',
    uuid: '',
    uploadedFiles: [], // my list for the v-for
    fileProgress: 0, // global progress
    allFilesUploaded: false // is everything done?
  },
  compinents: {},

  methods: {
    //高级搜索
    __find: function (inputQuery, pagenum, pagesteps) {
      var self = this;
      svc.find2('', pagenum, pagesteps, this.user, this.begtime, this.endtime, function (data, status, request) {
        self.$set("items", data);
        self.$set("curitem", self.items[0]);
      });
    },
    _find: function (inputQuery, pagenum, pagesteps) {
      var self = this;
      console.log("items", this.items);
      svc.find('', pagenum, pagesteps, this.items, function (data, status, request) {
        self.$set('items', data);
        if (self.items.length > 0) {
          self.$set("curitem", self.items[0]);
        }
      });
    },
    onRemove: function (item) {
      var self = this;
      var r = confirm("确定删除？");
      if (r == true) {
        svc.remove(item, function (data, status, request) {
            self.$set('curitem', item);
            self._find('', 1, 6);
          }
        )
      }
    },
    //返回到父节点
    backToParent: function () {
      var self = this;
      var p = this.items2.parent;
      console.log("backToParent " + p);
      //根节点
      if (p == null) {
        svc.find('', '', '', this.items, function (data, status, request) {
          self.$set('items', data);
          self.$set('items2', "");
          if (self.items.length > 0) {
            self.$set("curitem", self.items[0]);
          }
        });
      } else {
        svc.backToParent(p, function (data, status, request) {
          self.$set('items', data);
          svc.backToParent2(p, function (data2, status, request) {
            self.$set('items2', data2)
          });
        });
      }
    },
    //切换节点信息
    onChange: function (item) {
      var self = this;
      svc.change(item, function (data, status, request) {
        self.$set('items', data);
        //显示详情
        svc.details(item, function (data2, status, request) {
          self.$set('items2', data2)
        });
      });
    },
    //修改节点信息
    onEdit: function (item, mode) {
      console.log("edit onEdit")
      this.curitem=item;
      this.setMode(mode);
    },
    //下载附件
    download: function (item, mode) {
      console.log("downloading");
      console.log(item);
      if (item.originname.indexOf(".") == -1) {
        alert("文件夹不能下载");
      } else {
        var suffix = item.originname.substring(item.originname.lastIndexOf(".") + 1);
        var filename = item.uuid + "." + suffix;
        var day = item.crtdate.substr(0, 10);
        day = day.replace(/-/g, "");
        svc.downloading(filename, day, function (data, status, request) {
        });
      }
    },
    //上传附件(覆盖方式)
    //todo
    upload: function (item, mode) {

    },
    //显示全部信息
    basicsearch: function (e) {
      this._find(this.searchQuery, 1, 5);
    },
    //高级搜索
    advancedsearch: function (e) {
      console.log("advanced search");
      console.log(e.target.tagName); // "BUTTON"
      console.log(e.targetVM === this); // true

      var inputs = new Array(100);
      inputs[0] = "{begtime:'";
      inputs[1] = this.begtime;
      inputs[2] = "', endtime:'";
      inputs[3] = this.endtime;
      inputs[4] = "', user:'";
      inputs[5] = this.user;
      inputs[6] = "', searchQuery:'";
      inputs[7] = this.searchQuery;
      inputs[8] = "'}";

      var inputQuery = inputs.join('');
      console.log("your input query condition is " + inputQuery);
      this.__find(inputQuery, 2, 5);
    },
    onCancel: function () {
      console.log("onCancel");
      this.curitem={};
      this.setMode('modeList');
    },
    onSave: function (mode, item) {
      var uid = null;
      var self = this;
      var formData = new FormData(document.forms.namedItem("uploadForm"));
      console.log("onSave");
      if (mode == 'modeAddNew') {
        svc.add(item, function (data, status, request) {
          vm.uuid = data.uuid;
          var suffix = data.originname.substring(data.originname.lastIndexOf(".") + 1);
          formData.append('name', data.uuid + "." + suffix);
          formData.append('file', document.forms.namedItem("uploadForm"));
          svc.upload(formData);
          self.setMode('modeList');
        }, function (data, status, request) {
        });
        this.curitem={};
        this.setMode('modeList');
      }
      else {
        console.log("edit")
        self.$set("curitem.upduser", item.upduser);
        self.$set("curitem.curname", item.curname);
        svc.edit(this.curitem, function (item, status, request) {
        });
        this.curitem={};
        self.setMode('modeList');
      }
    }
    ,
    setMode: function (newmode) {
      if (this.mode != newmode) {
        this.mode = newmode;
        switch (newmode) {
          case "modeList":
            this.modeTitle = " [列表]";
            this.curitem.id = null;
            break;
          case "modeItemView":
            this.modeTitle = " [详情]";
            break;
          case "modeEdit":
            this.modeTitle = " [编辑]";
            this.currentView = "itemeditor";
            break;
          case "modeAddNew":
            this.modeTitle = " [新增]";
            this.currentView = "itemadd";
            break;
          default:
            this.modeTitle = "";
        }
      }
    }
  },
  ready: function () {
    this._find('', 1, 6);
  }
});

